package com.clusterswisdom.horn.api.push;

import java.io.IOException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.clusterswisdom.horn.api.ioc.api.HornConfig;

public class PushDataUtil {

	private ResfulApi api;
	
	public static PushDataUtil util = new PushDataUtil();
	
	public static PushDataUtil getUtil() {
		return util;
	}
	
	public String pushData(String uri, Object data) throws IOException {
		uri = parseUrl(uri);
		return api.sendNormalRequest(uri, formateParameter(data));
	}
	
	private String formateParameter(Object data) {
		return "requestData=" + JSON.toJSONString(data, SerializerFeature.QuoteFieldNames, SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteDateUseDateFormat, SerializerFeature.UseISO8601DateFormat);
	}
	
	private String parseUrl(String uri) {
		int bindex = uri.indexOf("${");
		int eindex = uri.indexOf("}");
		if (bindex == -1 || eindex == -1) {
			return uri;
		}
		
		String param = uri.substring(bindex + 2, eindex);
		return HornConfig.getConfig().getProperty(param) + uri.substring(eindex + 1);
	}
	
	private PushDataUtil() {
		this.api = new ResfulApi();
	}
	
}
